<?php


namespace App\Task;

use App\Models\Goods;
use App\Models\GoodsSku;
use App\Models\SeckillGoods;
use Hhxsv5\LaravelS\Swoole\Task\Task;
use Illuminate\Support\Facades\Redis;

class DecStockTask extends Task
{
    private $data;
    private $result;

    public function __construct($data)
    {
        $this->data = $data;
    }
    // 处理任务的逻辑，运行在Task进程中，不能投递任务
    public function handle()
    {
        \Log::info(__CLASS__ . ':handle start', [$this->data]);
//        sleep(2);// 模拟一些慢速的事件处理
        // throw new \Exception('an exception');// handle时抛出的异常上层会忽略，并记录到Swoole日志，需要开发者try/catch捕获处理
//        $this->result = 'the result of ' . $this->data;

        try{
            //减库存  先取队列
            $goods_id = $this->data['goods_id'];
            $sku_list = $this->data['sku'];
            $active_id = $this->data['active_id'];

            $stock_key = "dec_seckill_goods_stock:goods_id:$goods_id:active_id:$active_id";

            $before = Redis::lrange($stock_key,0,-1);
            var_dump($before);
            //\Log::info('异步减库存前长度:--' . $before);

            $decGoods = Redis::rpop($stock_key);

            $after = Redis::lrange($stock_key,0,-1);
            var_dump($after);
            //\Log::info('异步减库存后长度:--' . $after);

            //dec_seckill_goods_stock:goods_id:136:sku:35,42
            if($decGoods){

                //操作mysql 减库存

                //秒杀表
                SeckillGoods::query()->where([
                    'goods_id'=>$goods_id,
                    'id'=>$active_id
                ])->increment('sale_num',1);

                //库存表
                GoodsSku::query()->where([
                    'goods_id'=>$goods_id,
                    'sku_list'=>$sku_list
                ])->decrement('inventory',1);

                //商品主表
                Goods::query()->where(['id'=>$goods_id])->decrement('inventory',1);
                Goods::query()->where(['id'=>$goods_id])->increment('sales_num',1);

                //记录出队日志
                \Log::info('出库成功日志:--' . json_encode($this->data));
            }else{
                \Log::info('POP失败日志:--decGoods=' .$decGoods .'---数据：'. json_encode($this->data));
            }
        }catch (\Exception $e){
            \Log::info('【出库失败】--失败原因：'.$e->getMessage().'---'.json_encode($this->data));
        }
    }
    // 可选的，完成事件，任务处理完后的逻辑，运行在Worker进程中，可以投递任务
    public function finish()
    {

    }
}
